<?php
// +----------------------------------------------------------------------
// | @filename AdminUser.php
// +----------------------------------------------------------------------
// | @author 落花轻舞问君愁 <mwcx1990@qq.com>
// +----------------------------------------------------------------------
// | @datetime 2021-10-26 17:43:41
// +----------------------------------------------------------------------
// | @Description
// +----------------------------------------------------------------------


namespace Addons\Backend\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;

use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Support\Facades\Hash;
use Spatie\Permission\PermissionRegistrar;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Spatie\Permission\Traits\HasRoles;

class AdminUser extends Authenticatable implements JWTSubject
{
    use Notifiable;
    use HasRoles;
    use HasFactory;

    protected $guarded = [];

    protected $guard_name = 'backend';

    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    /**
     * Return a key value array, containing any custom claims to be added to the JWT.
     *
     * @return array
     */
    public function getJWTCustomClaims()
    {
        return [];
    }

    public function setPasswordAttribute($value)
    {
        $this->attributes['password'] = Hash::make($value);
    }

    public function roles(): BelongsToMany
    {
        $model_has_roles = config('permission.table_names.model_has_roles');

        return $this->morphToMany(
            Role::class,
            'model',
            $model_has_roles,
            config('permission.column_names.model_morph_key'),
            PermissionRegistrar::$pivotRole
        )
            ->where(function ($q) use ($model_has_roles) {
                $q->when(PermissionRegistrar::$teams, function ($q) use ($model_has_roles) {
                    $teamId = app(PermissionRegistrar::class)->getPermissionsTeamId();
                    $q->where($model_has_roles.'.'.PermissionRegistrar::$teamsKey, $teamId)
                        ->where(function ($q) use ($teamId) {
                            $teamField = config('permission.table_names.roles').'.'.PermissionRegistrar::$teamsKey;
                            $q->whereNull($teamField)->orWhere($teamField, $teamId);
                        });
                });
            });
    }
}
